<template>
  <!-- #ifndef H5 -->
  <u-navbar title="QC单" fixed border leftIcon="" leftText=""></u-navbar>
  <!-- #endif -->
  <!-- #ifdef H5 -->
  <u-navbar title="QC单" fixed border @leftClick="navigateBack" @rightClick="navigateHome">
    <template #right>
      <u-icon name="home" size="24"></u-icon>
    </template>
  </u-navbar>
  <!-- #endif -->
  <view class="page_wrap_container" :style="{ paddingTop: NavBarHeight + 'px' }">
    <scroll-view :style="{ height: windowHeight + 'px' }" scroll-y enable-flex :show-scrollbar="false"
      class="purchase_page_list" v-if="pagination.listData && pagination.listData.length > 0" @scrolltolower="loadMore">
      <view class="list_item" v-for="item in pagination.listData" :key="item.id">
        <view class="list_item_header">
          <view class="lih_title">{{ item.qualityOrderCode }}</view>
          <view class="lih_tag"><up-tag :text="item.qualityStatusName" :type="QC_COLOR_MAP[item.qualityStatus]"
              plain></up-tag></view>
        </view>
        <view class="list_item_info">
          <view class="lif_item">
            <view class="lifi_top">QC阶段：</view>
            <view class="lifi_main">{{ item.qualityPhaseName || '-' }}</view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">预约QC时间：</view>
            <view class="lifi_main">{{ item.actualQualityTime || '-' }}</view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">回复QC时间：</view>
            <view class="lifi_main">{{ item.replyQualityTime || '-' }}</view>
          </view>
          <view class="lif_item">
            <view class="lifi_top">实际QC时间：</view>
            <view class="lifi_main">{{ item.actualQualityTime || '-' }}</view>
          </view>
          <view class="lif_item" :style="{ 'padding-bottom': item?.detailVOS.length > 1 ? '50rpx' : '' }">
            <view class="lifi_top">关联采购单：</view>
            <view :class="{ 'lifi_main': true, 'lifi_main_text_ellipsis': (expandFlag && item?.detailVOS.length > 1) }">
              {{ item?.detailVOS?.reduce((acc: string, item: any, index: number) => {
    return acc + (index === 0 ? '' :
      ',') + item.purchaseOrderCode
  }, '') }}
            </view>
            <view class="look_more" v-if="item?.detailVOS.length > 1" @click.stop="toggleFlagChange"
              :style="{ background: expandFlag ? 'linear-gradient(-180deg, rgba(255, 255, 255, 0) 0%, #fff 100%)' : '' }">
              {{ expandFlag ? '展开更多' : '收起' }}<u-icon color="inherit" size="14"
                :name="!expandFlag ? 'arrow-up' : 'arrow-down'"></u-icon>
            </view>
          </view>

        </view>
        <!-- #ifndef H5 -->
        <view class="actions_box" @click.stop="orderQC(item)" v-if="item.qualityStatus == 1 || item.qualityStatus == 5">
          <view class="ab_btn">执行QC</view>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5 -->
        <view class="actions_box" @click.stop="replyQC(item)" v-if="item.qualityStatus == 1">
          <view class="ab_btn">回复QC</view>
        </view>
        <!-- #endif -->
      </view>
      <view class="has_data_text">
        <view class="no_more" v-if="!pagination.finished">加载中～</view>
        <view class="no_more" v-else>没有数据了～</view>
      </view>
      <view :style="{ height: '50px'}"></view>
    </scroll-view>
    <view class="empty_wrap" :style="{ height: windowHeight + 'px' }" v-else>
      <up-empty mode="order" text="暂无数据～">
      </up-empty>
    </view>
    <up-popup :show="popupFormQCShow" :round="10" @close="QCFormClose" closeOnClickOverlay>
      <view class="status_wrap_pop">
        <view class="pop_actions">
          <view class="reset_btn" @click="QCFormClose">关闭</view>
          <view class="confirm_btn" @click="popFormQCSave">保存</view>
        </view>
        <view class="form_wrap">
          <up-form labelAlign="right" ref="QCFormRef" :model="modalQC" labelWidth="130" :rules="formQCRules">
            <up-form-item label="实际QC时间：" prop="QC.actualQualityTime" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
                :title="modalQC.QC.actualQualityTime" :isLink="true" arrow-direction="down" :border="false"></up-cell>
            </up-form-item>
            <up-form-item label="是否通过：" prop="QC.passed" borderBottom>
              <up-radio-group v-model="modalQC.QC.passed" defa>
                <up-radio :customStyle="{ marginRight: '16px' }" v-for="(item, index) in radioOp" :key="index"
                  :label="item.name" :name="item.value">
                </up-radio>
              </up-radio-group>
            </up-form-item>
            <up-form-item label="备注：" prop="QC.remark" borderBottom>
              <up-textarea v-model="modalQC.QC.remark" placeholder="请输入备注" height="40" maxlength="100"></up-textarea>
            </up-form-item>
            <up-form-item label="QC报告：" prop="QC.fileId" borderBottom>
              <UploadImage v-model="modalQC.QC.fileId" @change="(val: string) => {
    modalQC.QC.fileId = val
  }"></UploadImage>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </up-popup>
    <up-popup :show="popupReplyFormQCShow" :round="10" @close="replyQCFormClose" closeOnClickOverlay>
      <view class="status_wrap_pop">
        <view class="pop_actions">
          <view class="reset_btn" @click="replyQCFormClose">关闭</view>
          <view class="confirm_btn" @click="popreplyFormQCSave">保存</view>
        </view>
        <view class="form_wrap">
          <up-form labelAlign="right" ref="replyQCFormRef" :model="modalReplyQC" labelWidth="130"
            :rules="formReplyQCRules">
            <up-form-item label="回复QC时间：" prop="QC.replyQualityTime" borderBottom>
              <up-cell :titleStyle="{ color: '#c1c4cc', fontSize: '15px' }" @click="handleShowDatePicker"
                :title="modalReplyQC.QC.replyQualityTime" :isLink="true" arrow-direction="down"
                :border="false"></up-cell>
            </up-form-item>
            <up-form-item label="QC人员：" prop="QC.qualityInspectorName" borderBottom>
              <up-input v-model="modalReplyQC.QC.qualityInspectorName" placeholder="请输入QC人员"></up-input>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </up-popup>
    <up-datetime-picker ref="datetimePickerRef" closeOnClickOverlay :show="datePickerShow" v-model="datetimeTime"
      mode="date" :formatter="formatter" @confirm="datePickerConfirm" @cancel="datePickerClose"
      @close="datePickerClose"></up-datetime-picker>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import HTTP from "@/utils/http"
import dayjs from "dayjs"
import { reactive } from "vue";
import type { PurchaseListType } from "./types"
import { onLoad } from "@dcloudio/uni-app";
import useScreenSize from "@/hooks/useScreenSize";
const { windowHeight, NavBarHeight, isIphoneX } = useScreenSize()
const navigateBack = () => {
  uni.navigateBack()
}
const navigateHome = () => {
  uni.switchTab({ url: "/pages/index/index" })
}
//获取页面 purchaseOrderCode
let purchaseOrderCode: string
let isReply: boolean
onLoad((options: any) => {
  purchaseOrderCode = options.purchaseOrderCode || ""
  isReply = options.isReply === '1'
})
const QC_COLOR_MAP: { [k: number | string]: any } = {
  1: 'info',
  2: 'success',
  3: 'warning',
  4: 'error',
  5: 'info',
  null: 'info'
}
const radioOp = [{ name: "是", value: 1 }, { name: "否", value: 0 }]
// 控制展开/折叠
const expandFlag = ref(true)
const toggleFlagChange = () => {
  expandFlag.value = !expandFlag.value
}
//DatePicker
const datetimeTime = ref(dayjs().format("YYYY-MM-DD"))
const datetimePickerRef = ref<any>(null);
const formatter = (type: string, value: string) => {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
};
const datePickerShow = ref(false)
const handleShowDatePicker = () => {
  datePickerShow.value = true
}
const datePickerConfirm = (event: any) => {
  datePickerShow.value = false
  datetimeTime.value = dayjs(event.value).format("YYYY-MM-DD")
  modalQC.QC.actualQualityTime = dayjs(event.value).format("YYYY-MM-DD")
  modalReplyQC.QC.replyQualityTime = dayjs(event.value).format("YYYY-MM-DD")
}
const datePickerClose = () => {
  datePickerShow.value = false
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalQC.QC.actualQualityTime = dayjs().format("YYYY-MM-DD")
  modalReplyQC.QC.replyQualityTime = dayjs().format("YYYY-MM-DD")
}
//popupFormQCShow
const QCFormRef = ref<any>(null)
const popupFormQCShow = ref(false)
const QCFormClose = () => {
  popupFormQCShow.value = false
  QCFormRef.value.resetFields()
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalQC.QC = {
    actualQualityTime: dayjs().format("YYYY-MM-DD"),
    passed: 1,
    remark: "",
    fileId: "",
  }
  modalReplyQC.QC.replyQualityTime = dayjs().format("YYYY-MM-DD")
}
const popFormQCSave = () => {
  QCFormRef.value.validate().then(() => {
    HTTP.POST({
      url: "sop/sop/quality/execute",
      isJson: true,
      data: { ...modalQC.QC, qualityOrderCode: currentInfo.value.qualityOrderCode },
      success: (res: any) => {
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          resetListData()
        }
      },
      complete: () => {
        QCFormClose()
      }
    })
  })
}
//popupReplyFormQCShow
const replyQCFormRef = ref<any>(null)
const popupReplyFormQCShow = ref(false)
const replyQCFormClose = () => {
  popupReplyFormQCShow.value = false
  replyQCFormRef.value.resetFields()
  datetimeTime.value = dayjs().format("YYYY-MM-DD")
  modalReplyQC.QC = {
    replyQualityTime: dayjs().format("YYYY-MM-DD"),
    qualityInspectorName: ""
  }
  modalQC.QC.actualQualityTime = dayjs().format("YYYY-MM-DD")
}
const popreplyFormQCSave = () => {
  replyQCFormRef.value.validate().then(() => {
    console.log(modalReplyQC.QC, '123123');
    const params = {
      replyQualityTime: modalReplyQC.QC.replyQualityTime,
      qualityInspectorName: modalReplyQC.QC.qualityInspectorName,
      qualityOrderCode: currentInfo.value.qualityOrderCode,
      qualityInspector: modalReplyQC.QC.qualityInspectorName
    }
    HTTP.POST({
      url: "sop/sop/quality/reply",
      isJson: true,
      data: params,
      success: (res: any) => {
        if (res.code == 200) {
          uni.showToast({
            title: '操作成功',
            icon: 'none',
          })
          resetListData()
        }
      },
      complete: () => {
        replyQCFormClose()
      }
    })
  })
}
//search
const resetListData = () => {
  resetPagination()
  getListData()
}
const resetPagination = () => {
  pagination.current = 1
  pagination.size = 10
  pagination.listData = []
  pagination.allcurrent = 1
  pagination.finished = false
}
//列表数据
onMounted(() => {
  datetimePickerRef.value && datetimePickerRef.value?.setFormatter(formatter);
  getListData()
})
const pagination = reactive<{ current: number, size: number, listData: PurchaseListType[], allcurrent: number, finished: boolean }>({
  current: 1, size: 10, listData: [], allcurrent: 1, finished: false
})
const getListData = async () => {
  if (pagination.current > pagination.allcurrent) return;
  const params = {
    current: pagination.current,
    size: pagination.size,
    purchaseOrderCode
  }
  HTTP.POST({
    url: "sop/sop/quality/query",
    isJson: true,
    data: params,
    success: (res: any) => {
      if (res.code == 200) {
        pagination.allcurrent = res.data.pageNum || 1
        pagination.listData = pagination.listData.concat(res?.data?.list || [])
        if (pagination.current + 1 > pagination.allcurrent) pagination.finished = true
        else pagination.finished = false
      } else {
        pagination.listData = []
      }
    }
  })
}
const loadMore = () => {
  pagination.current = pagination.current + 1
  getListData()
}
// actions
const currentInfo = ref<Record<string, any>>({})
const orderQC = (info: PurchaseListType) => {
  currentInfo.value = info
  popupFormQCShow.value = true
}
const replyQC = (info: PurchaseListType) => {
  currentInfo.value = info
  popupReplyFormQCShow.value = true
}
//form
const modalQC = reactive({
  QC: {
    actualQualityTime: dayjs().format("YYYY-MM-DD"),
    passed: 1,
    remark: "",
    fileId: "",
  }
})
const formQCRules = {
  'QC.actualQualityTime': { type: "string", required: true, message: "请选择实际QC时间", },
}
//form
const modalReplyQC = reactive({
  QC: {
    replyQualityTime: dayjs().format("YYYY-MM-DD"),
    qualityInspectorName: "",
  }
})
const formReplyQCRules = {
  'QC.replyQualityTime': { type: "string", required: true, message: "请选择回复QC时间", },
  'QC.qualityInspectorName': { type: "string", required: true, message: "请输入QC人员", },
}
</script>
<style lang="scss" scoped>
.page_wrap_container {
  display: flex;
  flex-direction: column;

  .purchase_page_list {
    .has_data_text {
      color: #aaa;
      text-align: center;
    }

    .list_item {
      margin: 24rpx 24rpx 0;
      background-color: #fff;
      display: flex;
      flex-direction: column;
      margin-bottom: 24rpx;
      border-radius: 18rpx;
      box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.08);
      overflow: hidden;

      .list_item_header {
        padding: 0 20rpx;
        height: 80rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .lih_title {
          flex: 1;
          font-weight: 500;
          text-overflow: ellipsis;
          white-space: nowrap;
          overflow: hidden;
          font-size: 34rpx;
        }

        .lih_tag {
          flex-shrink: 0;
        }
      }

      .list_item_info {
        display: flex;
        flex-direction: column;
        padding: 12rpx 20rpx;

        .lif_item {
          flex-shrink: 0;
          display: flex;
          flex-direction: row;
          margin-bottom: 12rpx;
          position: relative;
          flex-wrap: wrap;

          .lifi_top {
            flex-shrink: 0;
            margin-right: 12rpx;
            color: #888;
          }

          .lifi_main {
            flex: 1;
            flex-shrink: 0;
            color: #333;
            word-break: break-all;
            overflow-wrap: break-word;
          }

          .lifi_main_text_ellipsis {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .actions_box {
        border-top: 1px solid #f1f1f1;
        padding: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        .ab_btn {
          font-size: 30rpx;
          padding: 10rpx;
          color: $uni-color-primary;
        }
      }
    }

    .look_more {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      font-size: 28rpx;
      color: $uni-color-primary;
      margin-right: 4rpx;
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0rpx;
      padding-top: 100rpx;
    }
  }

  .empty_wrap {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}

.status_wrap_pop {
  padding: 30rpx;
  min-height: 300rpx;

  .form_wrap {
    width: 100%;
    padding: 24rpx 30rpx;

    .u-form-item__body__right .u-cell {
      width: 100%;
    }
  }

  .pop_actions {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .reset_btn {
      color: #888;
      padding: 12rpx;
    }

    .confirm_btn {
      color: $uni-color-primary;
      padding: 12rpx;
    }
  }

  .status_item {
    .status_item_title {
      padding: 30rpx 0;
      font-size: 36rpx;
      font-weight: 400;
      color: #333;
    }

    .status_item_btns_box {
      display: flex;
      flex-wrap: wrap;
      gap: 18rpx;

      .status_item_btn {
        border: 1px solid #ddd;
        padding: 10rpx 20rpx;
        color: #666;
      }

      .status_item_btn_active {
        border: 1px solid $uni-color-primary;
        background-color: $uni-color-primary;
        color: #fff;
      }
    }
  }
}
</style>
